//
//  LYComposeViewController.swift
//  微博
//
//  Created by liuerying on 16/5/28.
//  Copyright © 2016年 liuerying. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
class LYComposeViewController: UIViewController {

    //点击左上角关闭按钮事件
    @objc private func close(){
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func send(){
    
//        print("发送")
        
        
        LYNetworkTools.sharedTools.sendStatus(textView.fullText(), images: pictureSelector.images) { (responseObject, error) in
            
            
            print(responseObject)
            if error != nil{
                
                print(error)
                SVProgressHUD.showErrorWithStatus("发送微博失败")
                
                return
            }
                
                SVProgressHUD.showSuccessWithStatus("发送微博成功")

        }
        
    }
 
    
    
    @objc private func selectPicture(){
    
        print("选中图片")
        //当选中图片按钮时,弹出可添加图片的控制器及视图,更改它的高度
        pictureSelector.view.snp_updateConstraints { (make) in
            make.height.equalTo((ScreeHeight / 3) * 2)
        }
        
        
    }
    
    @objc private func selectEmoticon(){
    
        print("选择表情")
        
        textView.inputView = (textView.inputView == nil ) ? keyboardView : nil
        textView.reloadInputViews()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        
        setupUI()
        
        //注册通知
        registerNotification()

    }
    
    override func viewDidAppear(animated: Bool) {
  
        super.viewDidAppear(animated)
        //如果没有图片就是第一响应者
        if pictureSelector.images.count == 0 {
        
            //让文本视图成为第一响应者
            textView.becomeFirstResponder()

        }
  
    }
    //MARK:注册通知
    private func registerNotification(){
    
        //键盘值将要改变frame
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LYComposeViewController.keyBoardChane(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        //注册插入表情的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LYComposeViewController.insertEmoticon), name: EmoticonBtnDidClickNotification, object: nil)
    }
    
    
    //通知的
    @objc private func insertEmoticon(n: NSNotification) {
//        print(n.object)
        guard let em = n.object as? LYEmoticon else {
            return
        }
        //插入点击表情按钮对应的文字
        textView.insertEmoticon(em)
    }
    
    //移除通知
    deinit{
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //监听后的方法  键盘将要改变frame  toolBar需要做动画效果
    @objc private func keyBoardChane(n:NSNotification){
    
        print(n)
        //获取键盘显示或者隐藏的动画时间  --- 一般不用这样写  一般直接写0.25
        let time_t = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        //获取键盘frame改变后的frame
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey]as! NSValue).CGRectValue()

        //获取键盘的frame
        let offsetY = -ScreeHeight + rect.origin.y
        
        UIView.animateWithDuration(time_t) {
            //更新toolbar的底部约束  让它的底部约束相对于键盘弹出的高度,正好跟键盘重合
            self.toolBar.snp_updateConstraints(closure: { (make) in
                make.bottom.equalTo(offsetY)
            })
            
            //提前刷新页面
            self.view.layoutIfNeeded()
        }
    
    }
    
    //MARK: 添加UI界面
    private func setupUI(){
    
        setNavBar()
        setTextView()
        setToolBar()
        
        setSeletorPictureVC()
    }
    
    //添加照片视图与控制器
    private func setSeletorPictureVC(){
    
        //先将控制器添加进去
        self.addChildViewController(pictureSelector)
        //添加控制器View
        self.view.addSubview(pictureSelector.view)
     

        pictureSelector.view.snp_makeConstraints { (make) in
            make.left.bottom.right.equalTo(self.view)
//            make.height.equalTo((ScreeHeight / 3 ) * 2)
            
        }
        
        //让toolBar 上层
      self.view.bringSubviewToFront(toolBar)
    
    }
    
    //添加底部工具条
    private func setToolBar(){
    
        self.view.addSubview(toolBar)
        
        //默认有高度
        toolBar.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
        
        }
        
        var items = [UIBarButtonItem]()
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
                            ["imageName": "compose_mentionbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_trendbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
                            ["imageName": "compose_add_background","actionName": "selectPicture"]]
        
        //遍历数组
        for item in itemSettings{
        
            let imageName = item["imageName"]
            let action = item["actionName"]!
            
            //添加自定义的UIBarButtonItem
            let item = UIBarButtonItem(imageName: imageName, title: nil, target: self, action: Selector(action))
            
            items.append(item)
            
            //添加弹簧--平分frame
         let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
            
        }
        
        //移除最后一个弹簧
        items.removeLast()
        toolBar.items = items
        
    }
    
    //添加文本输入视图
    private func setTextView(){
    
        self.view.addSubview(textView)
        //设置文本输入视图的颜色
        textView.backgroundColor = UIColor(white: 0.8, alpha: 1)
        //设置约束
        textView.snp_makeConstraints { (make) in
            make.top.left.right.equalTo(self.view)

            //设置文本视图的高度是整个屏幕的三分之一
            make.height.equalTo(ScreeHeight / 3)
        }
        
        //把占位label添加到文本输入视图上
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) in
            make.left.equalTo(textView.snp_left).offset(5)
            make.top.equalTo(textView.snp_top).offset(8)
        }
        
    }
    
    
    
    //添加左边按钮
    private func setNavBar(){
    
        //添加左侧关闭按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem( title: "关闭", target: self, action: #selector(LYComposeViewController.close))
        
        //设置右边的饿按钮
        navigationItem.rightBarButtonItem = rightBarButtonItem
        
        //设置右边按钮默认不可以交互
        navigationItem.rightBarButtonItem?.enabled = false
        
//        print(navigationItem.titleView)
        
        let myView = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 40))
        
        let titleLabel = UILabel(title: "发布微博", font: 16, textcolor: UIColor.darkGrayColor())
       
        //微博的用户名
        let nameLabel = UILabel(title: LYUserAccountModel.sharedAccountViewModel.userAccount?.name ?? "", font: 14, textcolor: UIColor.darkGrayColor())
        
        myView .addSubview(titleLabel)
        myView.addSubview(nameLabel)
        
        
        titleLabel.snp_makeConstraints { (make) in
            make.centerX.equalTo(myView.snp_centerX)
            make.top.equalTo(myView.snp_top)
        }
        
        nameLabel.snp_makeConstraints { (make) in
            make.centerX.equalTo(myView.snp_centerX)
            make.bottom.equalTo(myView.snp_bottom)
        }
        
        navigationItem.titleView = myView
        
    }
    
    //MARK: 懒加载视图
    //懒加载键盘
    private lazy var keyboardView: LYEmoticonKeyBoardView = LYEmoticonKeyBoardView()
    
    //懒加载上传图片的控制器与视图
    private lazy var pictureSelector:LYPictuerController = LYPictuerController()
    //懒加载底部ToolBar
    private lazy var toolBar:UIToolbar = UIToolbar()
    
    
    //懒加载文本输入视图
    private lazy var textView:LYTextView = {
     let tv = LYTextView()
        
//        tv.text = "xiha"
        tv.font = UIFont.systemFontOfSize(15)
        tv.textColor = UIColor.darkGrayColor()
        
        //垂直可以拖拽 弹簧
        tv.alwaysBounceVertical = true
        
        //设置滚动视图 键盘消失的方式
        tv.keyboardDismissMode = .OnDrag
        
        tv.delegate = self
        
       return tv
    }()
    
    
    //懒加载占位文字的label
    private lazy var placeHolderLabel:UILabel = UILabel(title: "向阳生长", font: 18, textcolor: UIColor.lightGrayColor())

     
    
    //懒加载左边按钮
    private lazy var rightBarButtonItem:UIBarButtonItem = {
    
        let btn = UIButton()
        
        btn.setTitle("发送", forState: .Normal)
        //监听点击按钮
        btn.addTarget(self, action: #selector(LYComposeViewController.send), forControlEvents: .TouchUpInside)
        
        //设置按钮图片内容
        //设置文字
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        
        
        
        //设置背景图片
        btn.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), forState: .Highlighted)
        btn.setBackgroundImage(UIImage(named:"common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named:"common_button_white_disable"), forState: .Disabled)
        
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 30)
        
        let barButtonItem = UIBarButtonItem(customView: btn)
        
        return barButtonItem
 
    }()

}

//MARK: 文本输入视图的代理方法
extension LYComposeViewController:UITextViewDelegate{

    //文本输入发生改变
    func textViewDidChange(textView: UITextView) {
        //如果textView中有文字,就隐藏占位文字label
        placeHolderLabel.hidden = textView.hasText()
        //如果有文字,就让右边按钮可以点击发送
        rightBarButtonItem.enabled = textView.hasText()
    }
    
}
